﻿using WebMvc;
using System;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using System.Collections.Generic;
using Autofac;

using System.Linq;

public class MyDependencyResolver : IDependencyResolver
{
    private IContainer _container;
    public MyDependencyResolver(IContainer container)
    {
        _container = container;
    }
    public object GetService(Type serviceType)
    {
        if (!_container.IsRegistered(serviceType))
        {
            return null;
        }
        return _container.Resolve(serviceType);

    }

    public IEnumerable<object> GetServices(Type serviceType)
    {
        throw new NotImplementedException();
    }
}

 

public class CustomControllerActivator : IControllerActivator
{
    IController IControllerActivator.Create(
        System.Web.Routing.RequestContext requestContext,
        Type controllerType)
    {
        return DependencyResolver.Current
            .GetService(controllerType) as IController;
    }
}

public class MyControllerFactory : DefaultControllerFactory
{
    private IContainer _container;

    public MyControllerFactory(IContainer container)
    {
        _container = container;
    }
   

    protected override IController GetControllerInstance(RequestContext requestContext, Type controllerType)
    {
      
         
        //获取构造函数对象
        var constructor = controllerType.GetConstructors()[0];
        //获取构造函数参数
        var param = constructor.GetParameters();
        //获取构造函数所需的参数


        var paramNames = param.Select(a =>
        {
            try
            {

                
                return a.ParameterType.Name;
            }
            catch (Exception ex)
            {
                return null;
            }

        }).ToArray();
        IController controller = Activator.CreateInstance(controllerType, param) as Controller;
        return controller;
    }
}
 
